<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Device_model extends CI_Model {
	/**
	* __construct();
	* 初始化函数，从CI继承，必须初始化！
	* @access public
	* @no return
	  print($this->db->last_query());	// 输出最后一次执行的SQL语句
	*/
	public function __construct(){
		parent::__construct();
	}

	/**
		add_device 添加设备方法
		$parm array 数据数组

		添加之前有验证
		IP地址有重复的不让添加
		机器码重复的不让添加
	*/
	public function add_device($parm)
	{
		$ip = element('ip', $parm);	// IP
			$data = array(
				'ip' => $ip,
				'comment' => '暂无',
				'task' => '暂无',
				'progress' => '1/1'
			);
			$res = $this->db->select('*')->from('device')->where('ip', $parm['ip'])->get()->row();		// 根据IP查询 判断是否存在
			if(!$res){
				if($this->db->insert('device', $data)){
					return array(
						'ip' => $ip,
						"status" => "success",
						"reason" => "设备添加成功"
					);
				}else {
					return array(
						'ip' => $ip,
						"status" => "faild",
						"reason" => "设备添加失败"
					);
				}
			}else{
				return array(
					'ip' => $ip,
					"status" => "faild",
					"reason" => "设备已存在"
				);
			}

	}

	/**
		get_device_list 查询某个用户下所有设备方法
		$parm 条件参数数组
	*/
	public function get_device_list($parm)
	{
		$start = element('start', $parm);	// 数据开始位置
		$devicecount = count($this->db->get('device')->result_array());
		$start = ($start-1) * 15;
		$query = $this->db->get('device',15,$start);
		$result = array(
			"status" => "success",
			"device_count" => $devicecount,
			"page_id" => element('start', $parm),
			"device_list" => $query->result()
		);
		return $result;


	}
	/**
		get_device_where 先根据用户查询在根据ip和备注模糊查找
		$parm 条件参数数组
		$ip 默认为FALSE 如果为TRUE只返回IP
	*/
	public function get_device_where($parm,$ip=FALSE)
	{
		$start = element('start', $parm);	// 数据开始位置
		$like = element('like',$parm);	// 搜索数据条件
		// 设备总数
		$devicecount = count($this->db->select('*')->from('device')->or_like($like)->get()->result_array());
		$start = ($start-1) * 15;
		$query = $this->db->select('*')->from('device')->or_like($like)->limit(15,$start)->get();
		$result = array(
			"status" => "success",
			"device_count" => $devicecount,
			"page_id" => element('start', $parm),
			"device_list" => $query->result()
		);
		return $result;
	}
	public function update_ramark($parm)
	{
		$res = $this->db->where('id', $parm['id'])->update('device', $parm);
		return $res;
	}
	public function update_task($parm)
	{
		$res = $this->db->where('ip', $parm['ip'])->update('device', $parm);
		return $res;
	}
	public function update_progress($parm)
	{
		$res = $this->db->where('ip', $parm['ip'])->update('device', $parm);
		return $res;
	}
}
